import axios from "axios";

axios.defaults.baseURL = "/api";
axios.defaults.headers.common["Content-Type"] =
  "application/x-www-form-urlencoded";

export default {
  methods: {
    async getProject() {
      const { data: res } = await axios.get("/project");
      return res.data;
    },
    async getProjectConfigById(projectId) {
      const { data: res } = await axios.get(
        "/project/" + projectId.toString() + "/config"
      );
      return res;
    },
    async putProjectConfigById(projectId, projectConfig) {
      const { data: res } = await axios.put(
        "/project/" + projectId.toString() + "/config",
        projectConfig
      );
      return res;
    },
    async deleteProjectById(projectId) {
      const { data: res } = await axios.delete(
        "/project/" + projectId.toString()
      );
      return res.code;
    },
    async getProjectResource(projectId) {
      let { data: res } = await axios.get(
        "/project/" + projectId.toString() + "/resource",
        { responseType: "blob" }
      );
      if (res.code === "1007") {
        return {
          code: res.code,
          msg: res.msg,
        };
      }
      let blob = new Blob([res]);
      res = await this.getBlobData(blob);
      if (res.code === "1007") {
        return {
          code: res.code,
          msg: res.msg,
        };
      }
      let fileName = projectId.toString() + ".7z";
      //对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
      //IE10以上支持blob但是依然不支持download
      if ("download" in document.createElement("a")) {
        const link = document.createElement("a"); //创建a标签
        link.download = fileName; //a标签添加属性
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        document.body.appendChild(link);
        link.click(); //执行下载
        URL.revokeObjectURL(link.href); //释放url
        document.body.removeChild(link); //释放标签
      } else {
        //其他浏览器
        console.log("暂不支持该浏览器进行下载操作！建议使用Firefox 和 Chrome");
      }
      return {
        code: "200",
        msg: "已经在下载了，请等待...",
      };
    },
    getBlobData(file) {
      // eslint-disable-next-line no-unused-vars
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        reader.readAsText(file, "utf8");
        reader.onload = () => {
          try {
            let res = JSON.parse(reader.result);
            resolve(res);
          } catch (e) {
            resolve("");
          }
        };
      });
    },
  },
};
